import React, { Component } from 'react';

let currentId = 0;

interface ListItem {
  id: number;
  name: string;
}

interface State {
  count: number;
  list: ListItem[];
  inputValue: string;
  visible: boolean;
}

export default class App extends Component {
  // 管理页面状态
  state: State = {
    // state中的数据是只读的
    count: 0,
    list: [],
    inputValue: '',
    visible: true,
  };

  onAdd () {
    // tslint
    // no-any
    // const inp = document.querySelector('#inp') as HTMLInputElement;
    // const value = inp?.value;
    this.setState({
      inputValue: '',
      list: this.state.list.concat({
        name: this.state.inputValue,
        id: currentId++,
      }),
    });
  }

  onDelete (id: number) {
    this.setState({
      list: this.state.list.filter(item => item.id !== id),
    });
  }

  onInputChange (e: React.ChangeEvent) {
    this.setState({
      inputValue: (e.target as HTMLInputElement).value,
    });
  }

  toggleVisible () {
    this.setState({
      visible: !this.state.visible,
    });
  }

  // 官方提供的渲染函数
  render () {
    // jsx
    return (
      <div>
        <input
          value={ this.state.inputValue }
          onChange={ this.onInputChange.bind(this) }
          type="text"
        />
        <button onClick={ this.onAdd.bind(this) }>新增</button>
        {
          this.state.list.map((item) => {
            return (
              <div key={ item.id }>
                { item.name }
                <button onClick={ () => this.onDelete.call(this, item.id) }>删除</button>
              </div>
            );
          })
        }

        <button onClick={ this.toggleVisible.bind(this) }>显示/隐藏</button>
        {/* { this.state.visible ? <div>123</div> : null } */}
        { this.state.visible && <div>123</div> }

      </div>
    );
  }

}
